package com.gaogzhen.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.Config;
import com.gaogzhen.domain.Sms;
import com.gaogzhen.mapper.SmsMapper;
import com.gaogzhen.service.ConfigService;
import com.gaogzhen.service.SmsService;
import com.gaogzhen.config.sms.AliSms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @description ${description}
* @author Administrator
* @date 2022-06-07 11:46
* @version 1.0
*/
@Service
@Slf4j
public class SmsServiceImpl extends ServiceImpl<SmsMapper, Sms> implements SmsService{

    @Autowired
    private AliSms aliSms;

    @Autowired
    private ConfigService configService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendSms(Sms sms) {

        log.info("发送短信{}", JSON.toJSONString(sms, true));
        // 获取签名
        Config signConfig = configService.getByCode("SIGN");
        if (signConfig == null) {
            throw new RuntimeException("签名不存在");
        }
        // 获取短信模板code
        Config templateConfig = configService.getByCode(sms.getTemplateCode());
        if (templateConfig == null) {
            throw new IllegalArgumentException("短信模板不存在");
        }
        // 设置验证码
        String verifyCode = RandomUtil.randomNumbers(6);
        String templateParam = "{\"code\":\"" + verifyCode + "\"}";
        Map<String, Object> info = aliSms.sendSms(signConfig.getValue(), templateConfig.getValue(), templateParam, sms.getMobile());
        log.info("发送结果:{}", JSON.toJSONString(info, true));
        String code = String.valueOf(info.get("code"));
        if ("OK".equals(code)) {
            sms.setStatus(1);
            String content = "【" + signConfig.getValue() + "】" + templateConfig.getDesc().replaceAll("\\$\\{code}", verifyCode);
            sms.setContent(content);
            save(sms);
        } else {
            throw new RuntimeException("短信发送失败");
        }
        // 短信发送成功后，验证码保存到redis中，用于后续校验
        // key: SMS:VERIFY_OLD_PHONE  value：验证码
        redisTemplate.opsForValue().set("SMS:" + sms.getTemplateCode() + ":" + sms.getMobile(), verifyCode, 5, TimeUnit.MINUTES);
    }
}
